package com.bawei.module_goods.ui

import android.graphics.Color
import android.os.Bundle
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.widget.CompoundButton
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.bawei.module_goods.R
import com.bawei.module_goods.adapter.ShoppingCartAdapter
import com.bawei.module_goods.adapter.ShoppingCartAdapter.SwipeAction
import com.bawei.module_goods.databinding.ActivityShoppingCartBinding
import com.bawei.module_goods.network.GoodsApi
import com.bawei.module_goods.repository.ShoppingCartRepository
import com.yanzhenjie.recyclerview.SwipeMenuItem
import com.yanzhenjie.recyclerview.SwipeRecyclerView
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import com.bawei.lib_net.RetrofitFactory


@Route(path = "/module_goods/ShoppingCartActivity")
class ShoppingCartActivity : AppCompatActivity() {
    private lateinit var binding: ActivityShoppingCartBinding
    private lateinit var adapter: ShoppingCartAdapter
    private lateinit var repository: ShoppingCartRepository
    private var swipeJob: Job? = null
    private var priceDetailDialog: com.google.android.material.bottomsheet.BottomSheetDialog? = null
    private var tvTotalAmountInDialog: TextView? = null
    private lateinit var cartBottomBar: CartBottomBarView
    private var isEditMode = false
    private lateinit var viewModel: com.bawei.module_goods.viewmodel.ShoppingCartViewModel
    // 假设你有一个当前选中地址ID变量
    private var selectedAddressId: Long? = null // 你需要在地址选择逻辑中维护这个变量

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityShoppingCartBinding.inflate(layoutInflater)
        setContentView(binding.root)

        cartBottomBar = findViewById(R.id.cartBottomBar)

        repository = ShoppingCartRepository()
        adapter = ShoppingCartAdapter(
            onItemCheckedChange = { _, _ ->
                updateBottomBar()
                updateDialogTotalAmount()
            },
            onCountChange = { pos, count ->
                val item = adapter.getItem(pos)
                android.util.Log.d("CartLog", "Activity onCountChange pos=$pos, count=$count, item=$item")
                if (item != null) {
                    viewModel.dispatch(com.bawei.module_goods.intent.ShoppingCartIntent.UpdateCartItem(item.cartId, count))
                }
            },
            onSwipeAction = { position, action ->
                handleSwipeAction(position, action)
            }
        )
        binding.recyclerViewCart.layoutManager = LinearLayoutManager(this)
        // 先设置菜单
        (binding.recyclerViewCart as SwipeRecyclerView).setSwipeMenuCreator { leftMenu, rightMenu, viewType ->
            val deleteItem = SwipeMenuItem(this)
                .setBackground(R.color.red)
                .setText("删除")
                .setTextColor(Color.WHITE)
                .setWidth(180)
                .setHeight(MATCH_PARENT)
            rightMenu.addMenuItem(deleteItem)
            val collectItem = SwipeMenuItem(this)
                .setBackground(R.color.orange)
                .setText("收藏")
                .setTextColor(Color.WHITE)
                .setWidth(180)
                .setHeight(MATCH_PARENT)
            rightMenu.addMenuItem(collectItem)
        }
        (binding.recyclerViewCart as SwipeRecyclerView).setOnItemMenuClickListener { menuBridge, position ->
            menuBridge.closeMenu()
            when (menuBridge.position) {
                0 -> { // 删除
                    val item = adapter.getItem(position)
                    if (item != null) deleteCartItem(item.cartId)
                }
                1 -> { // 收藏
                    val item = adapter.getItem(position)
                    if (item != null) toggleCollect(item.goodsId)
                }
            }
        }
        // 最后设置adapter
        binding.recyclerViewCart.adapter = adapter
        
        // 新增：规格点击事件处理
        adapter.onSpecClick = { position, item ->
            // 通过goodsId获取商品详情，弹出规格弹窗
            lifecycleScope.launch {
                try {
                    val api = RetrofitFactory.getRetrofitFactory().create<GoodsApi>(GoodsApi::class.java)
                    val response = api.getGoodsDetail(item.goodsId)
                    if (response.code == 200 && response.data != null) {
                        val detail = response.data
                        val skuList = detail.skuList ?: emptyList()
                        val dialog = SkuSelectDialog(
                            skuList,
                            detail.mainImgUrl,
                            detail.purchasePrice?.toInt(),
                            detail.code
                        ) { model, quantity ->
                            // 选中后刷新购物车
                            viewModel.dispatch(com.bawei.module_goods.intent.ShoppingCartIntent.LoadCartList)
                        }
                        dialog.show(supportFragmentManager, "SkuSelectDialog")
                    } else {
                        Toast.makeText(this@ShoppingCartActivity, "获取商品详情失败", Toast.LENGTH_SHORT).show()
                    }
                } catch (e: Exception) {
                    Toast.makeText(this@ShoppingCartActivity, "网络异常", Toast.LENGTH_SHORT).show()
                }
            }
        }
        // 设置底部栏监听器
        setupBottomBarListeners()
        
        cartBottomBar.textDetail.setOnClickListener {
            showPriceDetailDialog()
        }
        cartBottomBar.btnCheckout.setOnClickListener {
            val checkedItems = adapter.getCheckedItems()
            if (checkedItems.isNotEmpty()) {
                val json = com.google.gson.Gson().toJson(checkedItems)
                com.alibaba.android.arouter.launcher.ARouter.getInstance()
                    .build("/module_mine/ConfirmOrderActivity")
                    .withString("cartItemsJson", json)
                    .withString("addressId", selectedAddressId?.toString() ?: "")
                    .navigation(this)
            } else {
                Toast.makeText(this, "请先选择商品", Toast.LENGTH_SHORT).show()
            }
        }
        binding.ivBack.setOnClickListener { finish() }
        loadCartData()
        fun selectTab(index: Int) {
            binding.tabAll.setTextColor(if (index == 0) getColor(R.color.tab_selected) else getColor(R.color.tab_normal))
            binding.tabInvalid.setTextColor(if (index == 1) getColor(R.color.tab_selected) else getColor(R.color.tab_normal))
            binding.tabFilter.setTextColor(if (index == 2) getColor(R.color.tab_selected) else getColor(R.color.tab_normal))
        }
        binding.tabAll.setOnClickListener { selectTab(0) }
        binding.tabInvalid.setOnClickListener { selectTab(1) }
        binding.tabFilter.setOnClickListener { selectTab(2) }
        selectTab(0)
        // 编辑/完成按钮切换
        binding.tvEdit.setOnClickListener {
            isEditMode = !isEditMode
            binding.tvEdit.text = if (isEditMode) "完成" else "编辑"
            cartBottomBar.setEditMode(isEditMode)
            updateBottomBar()
        }

        // 初始化 viewModel
        viewModel = ViewModelProvider(this)[com.bawei.module_goods.viewmodel.ShoppingCartViewModel::class.java]

        // 监听 ViewModel 的 state，自动刷新购物车列表（StateFlow收集方式）
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.state.collect { state ->
                    when (state) {
                        is com.bawei.module_goods.state.ShoppingCartState.Success -> {
                            adapter.setData(state.items)
                            updateBottomBar()
                            binding.tabAll.text = "全部(${adapter.itemCount})"
                        }
                        is com.bawei.module_goods.state.ShoppingCartState.Loading -> {
                            // 可选：显示加载中
                        }
                        is com.bawei.module_goods.state.ShoppingCartState.Error -> {
                            android.widget.Toast.makeText(this@ShoppingCartActivity, state.msg, android.widget.Toast.LENGTH_SHORT).show()
                        }
                        else -> {}
                    }
                }
            }
        }

        // 页面初始化时加载购物车数据
        viewModel.dispatch(com.bawei.module_goods.intent.ShoppingCartIntent.LoadCartList)
    }

    // 设置底部栏监听器
    private fun setupBottomBarListeners() {
        // 普通模式全选监听器
        cartBottomBar.checkboxSelectAll.setOnCheckedChangeListener(checkboxSelectAllListener)
        
        // 编辑模式全选监听器
        cartBottomBar.checkboxSelectAllEdit.setOnCheckedChangeListener(checkboxSelectAllEditListener)
        
        // 编辑模式批量删除
        cartBottomBar.btnDelete.setOnClickListener {
            val checkedItems = adapter.getCheckedItems()
            if (checkedItems.isEmpty()) {
                Toast.makeText(this, "请选择要删除的商品", Toast.LENGTH_SHORT).show()
            } else {
                // 批量删除
                CoroutineScope(Dispatchers.IO).launch {
                    checkedItems.forEach { item ->
                        repository.deleteCartItem(item.cartId)
                    }
                    withContext(Dispatchers.Main) {
                        loadCartData()
                        Toast.makeText(this@ShoppingCartActivity, "删除${checkedItems.size}件商品", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }
        // 编辑模式批量收藏
        cartBottomBar.btnCollect.setOnClickListener {
            val checkedItems = adapter.getCheckedItems()
            if (checkedItems.isEmpty()) {
                Toast.makeText(this, "请选择要收藏的商品", Toast.LENGTH_SHORT).show()
            } else {
                // 批量收藏
                CoroutineScope(Dispatchers.IO).launch {
                    checkedItems.forEach { item ->
                        repository.toggleCollect(item.goodsId)
                    }
                    withContext(Dispatchers.Main) {
                        Toast.makeText(this@ShoppingCartActivity, "收藏${checkedItems.size}件商品", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }
    }

    private fun loadCartData() {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val displayItems = com.bawei.module_goods.repository.ShoppingCartRepository().getCartDisplayList()
                withContext(Dispatchers.Main) {
                    adapter.setData(displayItems)
                    updateBottomBar()
                    binding.tabAll.text = "全部(${adapter.itemCount})"
                    Toast.makeText(this@ShoppingCartActivity, "加载到${displayItems.size}条数据", Toast.LENGTH_SHORT).show()
                }
            } catch (e: Exception) {
                e.printStackTrace()
                android.util.Log.e("ShoppingCart", "请求异常: "+e.message)
            }
        }
    }

    // 普通模式全选监听器
    private val checkboxSelectAllListener = CompoundButton.OnCheckedChangeListener { _, isChecked ->
        adapter.setAllChecked(isChecked)
        updateBottomBar()
        updateDialogTotalAmount()
    }
    // 编辑模式全选监听器
    private val checkboxSelectAllEditListener = CompoundButton.OnCheckedChangeListener { _, isChecked ->
        adapter.setAllChecked(isChecked)
        updateBottomBar()
        updateDialogTotalAmount()
    }

    private fun updateBottomBar() {
        val checkedItems = adapter.getCheckedItems()
        val total = checkedItems.sumOf { (it.price ?: 0.0) * (if ((it.number ?: 0) > 0) it.number!! else 1) }
        cartBottomBar.setEditMode(isEditMode)
        if (isEditMode) {
            cartBottomBar.setCheckedAllEdit(checkedItems.size == adapter.itemCount && adapter.itemCount > 0, checkboxSelectAllEditListener)
            cartBottomBar.setDeleteCount(checkedItems.size)
            cartBottomBar.setCollectCount(checkedItems.size)
        } else {
            cartBottomBar.setTotalPrice(total)
            cartBottomBar.setCheckoutCount(checkedItems.size)
            cartBottomBar.setCheckedAll(checkedItems.size == adapter.itemCount && adapter.itemCount > 0, checkboxSelectAllListener)
            cartBottomBar.btnCheckout.isEnabled = checkedItems.isNotEmpty()
            if (checkedItems.isNotEmpty()) {
                cartBottomBar.btnCheckout.setBackgroundColor(resources.getColor(R.color.red))
            } else {
                cartBottomBar.btnCheckout.setBackgroundColor(resources.getColor(R.color.tab_normal))
            }
        }
    }

    private fun handleSwipeAction(position: Int, action: SwipeAction) {
        val item = adapter.getItem(position) ?: return
        when (action) {
            SwipeAction.DELETE -> deleteCartItem(item.cartId)
            SwipeAction.COLLECT -> toggleCollect(item.goodsId)
        }
    }

    private fun deleteCartItem(cartId: Int) {
        swipeJob?.cancel()
        swipeJob = CoroutineScope(Dispatchers.IO).launch {
            val success = repository.deleteCartItem(cartId)
            withContext(Dispatchers.Main) {
                if (success) {
                    Toast.makeText(this@ShoppingCartActivity, "删除成功", Toast.LENGTH_SHORT).show()
                    loadCartData()
                } else {
                    Toast.makeText(this@ShoppingCartActivity, "删除失败", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    private fun toggleCollect(goodsId: Int) {
        swipeJob?.cancel()
        swipeJob = CoroutineScope(Dispatchers.IO).launch {
            val success = repository.toggleCollect(goodsId)
            withContext(Dispatchers.Main) {
                if (success) {
                    Toast.makeText(this@ShoppingCartActivity, "操作成功", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(this@ShoppingCartActivity, "操作失败", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    private fun showPriceDetailDialog() {
        val dialog = com.google.android.material.bottomsheet.BottomSheetDialog(this)
        val dialogView = layoutInflater.inflate(R.layout.dialog_cart_price_detail, null)
        val tvTotalAmount = dialogView.findViewById<TextView>(R.id.tvTotalAmount)
        val tvDiscount = dialogView.findViewById<TextView>(R.id.tvDiscount)
        val ivClose = dialogView.findViewById<ImageView>(R.id.ivClose)
        tvTotalAmountInDialog = tvTotalAmount
        priceDetailDialog = dialog
        updateDialogTotalAmount() // 初始金额
        ivClose.setOnClickListener { dialog.dismiss() }
        dialog.setContentView(dialogView)
        dialog.show()
    }

    private fun updateDialogTotalAmount() {
        tvTotalAmountInDialog?.let {
            val checkedItems = adapter.getCheckedItems()
            val total = checkedItems.sumOf { (it.price ?: 0.0) * (if ((it.number ?: 0) > 0) it.number!! else 1) }
            it.text = "￥${total.toInt()}"
        }
    }
} 